import Vue from "vue"
import Vuex from "vuex"
import tabBar from './tebBar.js';
import { apiUploadImage } from "@/api/index.js";
import { Toast } from "vant"; // 确保导入 Toast

Vue.use(Vuex);
const store = new Vuex.Store({
    state: {
        userAgreement: true, //初次渲染用户协议
        uploadedImages: [] // 存储上传的图片信息
    },
    mutations: {
        // 用户协议是否展示
        CHANGE_SHOW(state, userAgreement) {
            state.userAgreement = userAgreement;
        },
        // 添加上传的图片
        ADD_UPLOADED_IMAGE(state, image) {
            state.uploadedImages.push(image);
            // 同时保存到本地存储
            localStorage.setItem('uploadedImages', JSON.stringify(state.uploadedImages));
        },


        // 初始化图片列表（从本地存储加载）
        INIT_UPLOADED_IMAGES(state) {
            const savedImages = localStorage.getItem('uploadedImages');
            if (savedImages) {
                state.uploadedImages = JSON.parse(savedImages);
            }
        },
        REMOVE_UPLOADED_IMAGE(state, imageId) {
            // 1. 从 Vuex 状态中删除指定 ID 的图片
            state.uploadedImages = state.uploadedImages.filter(img => img.id !== imageId);
            // 2. 同步更新本地存储（确保刷新后状态一致）
            localStorage.setItem('uploadedImages', JSON.stringify(state.uploadedImages));
        },
        // 清空图片列表
        CLEAR_UPLOADED_IMAGES(state) {
            state.uploadedImages = [];
            localStorage.removeItem('uploadedImages');
        }
    },
    actions: {
        // 异步上传图片
        async uploadImage({ commit }, file) {
            try {
                // 调用上传接口
                const response = await apiUploadImage(file);
                console.log("🚀 ~ uploadImage ~ response:", response)
                    // 假设接口返回的数据格式为 { id, url, ... }
                if (response.data.code === 0 && response.data.data) {
                    commit('ADD_UPLOADED_IMAGE', response.data.data.data);
                    return response.data.data.data;
                }
                throw new Error('图片上传失败');
            } catch (error) {
                console.error('上传图片出错:', error);
                throw error;
            }
        },

        // 删除图片
        deleteImage({ commit }, imageId) {
            return new Promise((resolve, reject) => {
                try {
                    // 调用 Mutation 执行删除
                    commit('REMOVE_UPLOADED_IMAGE', imageId);
                    resolve(); // 告知组件删除成功
                } catch (error) {
                    reject(error); // 告知组件删除失败
                }
            });
        }
    },
    getters: {
        // 获取上传的图片列表
        getUploadedImages: state => state.uploadedImages
    },
    modules: {
        tabBar, // 注册 tabBar 模块
    },
})
export default store